package com.daiziru.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.daiziru.VO.UserMessageVO;
import com.daiziru.common.Result;
import com.daiziru.entity.MPost;
import com.daiziru.entity.MUser;
import com.daiziru.entity.MUserMessage;
import com.daiziru.service.MUserService;
import com.daiziru.shiro.AccountProfile;
import com.daiziru.util.UploadUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 作者：無言
 * 时间：2022/12/17 16:06
 * 描述：永无BUG
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private MUserService userService;

    @Autowired
    private UploadUtil uploadUtil;

    @GetMapping("/home")
    public String userHome() {
        MUser user = userService.getById(getProfile().getId());
        //获取发表的文章
        List<MPost> posts = postService.list(new QueryWrapper<MPost>()
                .eq("user_Id", user.getId())
                .gt("created", DateUtil.offsetDay(new Date(), -30))
                .orderByDesc("created")
        );

        req.setAttribute("user", user);
        req.setAttribute("posts", posts);

        return "/user/home";
    }

    @GetMapping("/set")
    public String userSet(){
        MUser user = userService.getById(getProfile().getId());
        req.setAttribute("user", user);
        return "/user/set";
    }
    @ResponseBody
    @PostMapping("/set")
    public Result doSet(MUser user) {

        if(StrUtil.isBlank(user.getUsername())) {
            return Result.fail("昵称不能为空!");
        }
        int count = userService.count(new QueryWrapper<MUser>()
                .eq("username", user.getUsername())
                .ne("id", getProfile().getId())
        );
        if(count > 0) {
            return Result.fail("昵称已被占用！");
        }
        MUser tempUser = userService.getById(getProfile().getId());
        tempUser.setUsername(user.getUsername());
        tempUser.setGender(user.getGender());
        tempUser.setSign(user.getSign());
        userService.updateById(tempUser);
        //更新session中的用户信息
        AccountProfile profile = getProfile();
        profile.setUsername(tempUser.getUsername());
        profile.setSign(tempUser.getSign());
        SecurityUtils.getSubject().getSession().setAttribute("profile", profile);
        return Result.success().action("/user/set#info");
    }


    @ResponseBody
    @PostMapping("/upload")
    public Result uploadAvatar(@RequestParam(value = "file") MultipartFile file) throws IOException {
        Result upload = uploadUtil.upload(UploadUtil.type_avatar, file);
        return upload;
    }

    @ResponseBody
    @PostMapping("/postImg")
    public Result uploadPostImg(@RequestParam(value = "file") MultipartFile file) throws IOException {
        Result upload = uploadUtil.upload(UploadUtil.type_post_img, file);
        upload.getData();
        return upload;
    }


    @PostMapping("/updateAvatar")
    public Result updateAvatar(String avatarUrl) {
        if(StrUtil.isNotBlank(avatarUrl)) {
            MUser temp = userService.getById(getProfile().getId());
            temp.setAvatar(avatarUrl);
            userService.updateById(temp);
            AccountProfile profile = getProfile();
            profile.setAvatar(avatarUrl);
            SecurityUtils.getSubject().getSession().setAttribute("profile", profile);
            return Result.success().action("/user/set#avatar");
        }
        return Result.fail("上传失败");
    }


    @ResponseBody
    @PostMapping("/repass")
    public Result repass(String nowpass, String pass, String repass) {
        //校验当前输入的两次密码一不一致
        if(!pass.equals(repass)) {
            return Result.fail("两次输入的密码不一致！");
        }
        MUser user = userService.getById(getProfile().getId());
        String passwordMd5 = SecureUtil.md5(nowpass);
        //检验输入的密码是否和数据库的一致
        if(!passwordMd5.equals(user.getPassword())) {
            return Result.fail("输入密码错误！");
        }
        user.setPassword(SecureUtil.md5(pass));
        userService.updateById(user);

        SecurityUtils.getSubject().getSession().removeAttribute("profile");
        return Result.success("修改密码成功,请重新登陆！", null).action("/authority/login");
    }

    @GetMapping("/index")
    public String index() {
        return "/user/index";
    }
    @GetMapping("/mess")
    public String mess() {
        IPage<UserMessageVO> page = messageService.paging(getPage(), new QueryWrapper<MUserMessage>()
                .eq("to_user_id", getProfile().getId())
                .orderByDesc("created")
        );

        // 把消息改成已读状态
        List<Long> ids = new ArrayList<>();
        for(UserMessageVO messageVo : page.getRecords()) {
            if(messageVo.getStatus() == 0) {
                ids.add(messageVo.getId());
            }
        }
        // 批量修改成已读
        messageService.updateToReaded(ids);
        req.setAttribute("pageData", page);
        return "/user/mess";
    }

    @ResponseBody
    @PostMapping("/message/remove/")
    public Result msgRemove(Long id,
                            @RequestParam(defaultValue = "false") Boolean all) {

        boolean remove = messageService.remove(new QueryWrapper<MUserMessage>()
                .eq("to_user_id", getProfile().getId())
                .eq(!all, "id", id)); //all==true则删除全部消息
        return remove ? Result.success(null) : Result.fail("删除失败");
    }

    /**
     * 新的未读消息提示
     * @return
     */
    @ResponseBody
    @RequestMapping("/message/nums/")
    public Map msgNums() {

        int count = messageService.count(new QueryWrapper<MUserMessage>()
                .eq("to_user_id", getProfile().getId())
                .eq("status", "0")
        );
        return MapUtil.builder("status", 0)
                .put("count", count).build();
    }


    @ResponseBody
    @GetMapping("/public")
    public Result userP() {
        IPage page = postService.page(getPage(),new QueryWrapper<MPost>()
                .eq("user_id", getProfile().getId())
                .orderByDesc("created")
        );
        return Result.success(page);
    }

    @ResponseBody
    @GetMapping("/collection")
    public Result collection() {
        /**
         * select * from m_post p LEFT JOIN m_user_collection c on p.id = c.post_id
         * where p.user_id = c.user_id
         * sql优化（未优化可以使用left join的写法）
         * select * from m_post where id in (
         * 	select post_id From m_user_collection where user_id = 12
         * )limit 0, 10;
         */
        IPage page = postService.page(getPage(), new QueryWrapper<MPost>()
                .inSql("id", "select post_id From m_user_collection where user_id = " + getProfile().getId())
        );
        return Result.success(page);
    }




}
